import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor
from pandas.plotting import register_matplotlib_converters
from enum import Enum

import QUANTAXIS as QA

register_matplotlib_converters()


# list = [9, 8, 9, 7, 9, 8, 9, 10, 8, 9,
#         9, 8, 5, 7, 6, 5, 3, 1, 2, 1,
#         2, 1, 3, 1, 2, 3, 4, 3, 1, 1,
#         2, 1, 2, 3, 1, 2, 1, 3, 2, 1,
#         2, 3, 4, 3, 2, 3, 4, 5, 6, 7]
# n = 20
# s = pd.Series(list)
# smax = s.rolling(n).max()
# smin = s.rolling(n).min()
# sstd = s.rolling(n).std()
# savg = s.rolling(n).sum()
# sdif = s.diff(1)
# sdif2 = sdif.diff(1)
# sdif_sum = s.diff(n).rolling(5).sum()
# df = pd.DataFrame({'data': s, 'max': smax, 'min': smin, 'avg': savg, 'diff': sdif, 'std': sstd,
#                    'dif_sum': sdif_sum})
# tmp = pd.Series([1, 2, 3, 4, 5, 6, 7])
# df.iat[0, :] = 1000
# print(df)
# # df_r.plot()
# figure = plt.figure()
# axes1 = figure.add_subplot(411)
# axes2 = figure.add_subplot(412)
# axes3 = figure.add_subplot(413)
# axes4 = figure.add_subplot(414)
# axes1.plot(df.index, df[['data', 'max']])
# axes2.plot(df.index, df[['data', 'min']])
# axes3.plot(df.index, df[['data', 'diff']])
# axes4.plot(df.index, df[['diff', 'dif_sum']])
# multi = MultiCursor(figure.canvas, (axes1, axes2, axes3, axes4), color='r', lw=1)
# plt.show()

# res = QA.QA_fetch_financial_report(['603788'], ['2020-03-31'])
# print(res.head())
# res.to_csv('603788.csv')
# res = res.reset_index()
# print(res.head())

# import tushare as ts
# df = ts.get_report_data(2020, 2)
# df.to_csv('report.csv', encoding='utf_8_sig')

# import baostock as bs
# import pandas as pd
#
# #### 登陆系统 ####
# lg = bs.login()
# # 显示登陆返回信息
# print('login respond error_code:'+lg.error_code)
# print('login respond  error_msg:'+lg.error_msg)
#
# #### 获取公司业绩快报 ####
# rs = bs.query_performance_express_report("sh.601633", start_date="2020-01-01", end_date="2020-12-31")
# print('query_performance_express_report respond error_code:'+rs.error_code)
# print('query_performance_express_report respond  error_msg:'+rs.error_msg)
#
# result_list = []
# while (rs.error_code == '0') & rs.next():
#     result_list.append(rs.get_row_data())
#     # 获取一条记录，将记录合并在一起
# result = pd.DataFrame(result_list, columns=rs.fields)
# #### 结果集输出到csv文件 ####
# result.to_csv("performance_express_report.csv", encoding="gbk", index=False)
# print(result)
# # 没有及时更新啊，长城中报快报在2020.07.29没有显示出来
#
# #### 登出系统 ####
# bs.logout()

# def avg(row):
#     count = 0
#     sum = 0
#     for item in row:
#         if item != 0.2 and item != 0.8:
#             sum += item
#             count += 1
#     return sum / count
#
# import numpy as np
# df = pd.DataFrame(np.random.random([5, 6]))
# df.clip(lower=0.2, upper=0.8, inplace=True)
# print(df)
# df['score'] = df.apply(lambda x: avg(x), axis=1)
# print(df)

import datetime
# old_data = QA.QA_fetch_stock_min('000002', QA.QA_util_get_last_day(QA.QA_util_get_real_date(str(datetime.date.today()))),
#                                                str(datetime.datetime.now()), format='pd',
#                                                frequence='1m').set_index(['datetime', 'code'])

# old_data = QA.QA_fetch_stock_min('000100', '2020-07-15', '2020-07-16', format='pd', frequence='1m')\
#      .set_index(['datetime', 'code'])

# index_list = QA.QA_fetch_index_list_adv()
# index_list.to_csv('test.csv', encoding='utf_8_sig')

# today = datetime.date.today()
# last_year = datetime.date.today() + datetime.timedelta(days=-365)
# last_week = datetime.date.today() + datetime.timedelta(days=-7)
# last_month = datetime.date.today() + datetime.timedelta(days=-30)
#
# start = last_year.strftime('%Y-%m-%d')
# end = today.strftime('%Y-%m-%d')
# # 880301到880685  8803到8806开头
# jg = QA.QA_quotation(['880391'], last_week, today,
#                      frequence=QA.FREQUENCE.DAY, market=QA.MARKET_TYPE.INDEX_CN,
#                      source=QA.DATASOURCE.MONGO, output=QA.OUTPUT_FORMAT.DATASTRUCT)
# print(jg.data.head())

# import tushare as ts
# #
# ts_token = '17056d23a59ab71cb979c6a30185e092aba605c4544dac900a3eb7f8'
# ts.set_token(ts_token)
# pro = ts.pro_api()
# # data = pro.moneyflow_hsgt(start_date='20141117', end_date='20150701')
# # data = pro.hk_hold(trade_date='20160629')
# data = pro.margin(trade_date='20210114')
# print(data)
# # data.to_csv('test.csv', encoding='utf_8_sig')

# data = pro.stock_basic(exchange='', list_status='L')
# data.to_csv('stocks.csv', encoding='utf_8_sig')

old_data = QA.QA_fetch_stock_day_adv(['000100', '000001'], '2020-07-15', '2020-07-17').data
new_data = QA.QA_fetch_stock_day_adv(['000100', '000001'], '2020-07-16', '2020-07-18').data
# new_data = new_data.drop(labels=0)
new_data.iloc[0, 0] = 1
print(old_data)
print(new_data)
# df = pd.merge(old_data, new_data, how='outer', left_index=True, right_index=True)
inter = new_data.index.levels[0].intersection(old_data.index.levels[0])
print(inter)
# old_data = old_data[old_data.index.levels[0].isin(inter)]
old_data = old_data.drop(index=inter)
print(old_data)
df = old_data.append(new_data)
print(df)
# df1 = df.loc[df.index.levels[0][-1], :]
# df2 = df.loc[df.index.levels[0][-2], :]
# df3 = df.loc[df.index.levels[0][-3], :]
# # l = [df1[['close', 'low']], df2[['close', 'low']], df3[['close', 'low']]]
# l = [df[['close', 'low']], df[['close', 'low']], df[['close', 'low']]]
# # print(df1 + df2 + df3)
# tmp = l[0]
# for d in l:
#     tmp += d
# print(tmp)

def x1(item):
    print(item)

tmp = df.groupby(level=0).apply(x1)

